﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Text.Json;
using System.Threading.Tasks;

namespace AvalSqlIndexManager.Models
{
    public static class JsonHelper
    {
        // 序列化对象为 JSON 字符串
        public static string Serialize<T>(T obj)
        {
            try
            {
                var options = new JsonSerializerOptions
                {
                    WriteIndented = true, // 格式化输出
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase, // 使用驼峰命名
                    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull // 忽略 null 属性
                };
                return JsonSerializer.Serialize(obj, options);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("序列化失败", ex);
            }
        }

        // 反序列化 JSON 字符串为对象
        public static T? Deserialize<T>(string json)
        {
            try
            {
                var options = new JsonSerializerOptions
                {
                    WriteIndented = true, // 格式化输出
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase, // 使用驼峰命名
                    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull // 忽略 null 属性
                };
                return JsonSerializer.Deserialize<T>(json,options);
            }
            catch (JsonException ex)
            {
                throw new InvalidOperationException("反序列化失败", ex);
            }
        }
    }
}
